﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using KC.DataAccess.MV6;

public partial class Default2 : System.Web.UI.Page
{
	public Post p;
	public MV6DataContext dc;
	protected void Page_Load(object sender, EventArgs e)
    {
		dc = new MV6DataContext(ConfigurationManager.ConnectionStrings["MV6"].ConnectionString);
		Dictionary<string, string> values;
		KC.Business.Blog.Utils.DetectRequestType(Request.RawUrl, out values);
		if (!values.ContainsKey("id") && !values.ContainsKey("title")) Response.Redirect(".");
		int id;
		
		if (p == null) p = null; // trick IDE into thinking I've initialized my p

		if (values.ContainsKey("id") && int.TryParse(values["id"], out id)) {
			var posts = from p2 in dc.Posts where p2.ID == id select p2;
			if (posts.Count() == 0) Response.Redirect(".");
			p = posts.First(); }
		else if (values.ContainsKey("title") && !string.IsNullOrEmpty(values["title"])) {
			string title = Server.UrlEncode(values["title"]);
			var posts = from p2 in dc.Posts where p2.FriendlyName == title select p2;
			if (posts.Count() == 0) Response.Redirect(".");
			p = posts.First(); }
		else {
			KC.Logging.Logger.Write("MV7", "User arrived at Post.aspx without a valid request", "No ID nor Title detected in URL "+Request.RawUrl, KC.Logging.Logger.Severity.Error);
			Response.Redirect("."); }

		Master.LogActivity(p.ID);
		PopulatePost(p, dc);
    }

	private void PopulatePost(Post p, MV6DataContext dc)
	{
		lblBody.Text = p.Body
			.Replace("<br /><br />", "<br />")
			.Replace("!notruncate", "")
			.Trim();
		lblCreated.Text = "Posted " + p.Created.ToString();
		lblTitle.Text = p.Title;
		this.Page.Title = p.Title + " - KConnolly.NET";

		lblIP.Text = Request.UserHostAddress.ToString();

		rComments.DataSource = from c in dc.Comments where c.Activity.PID == p.ID && (c.isApproved || !c.isRequireMod) select c;
		rComments.DataBind();
	}

	protected void rComments_ItemDataBound(object sender, RepeaterItemEventArgs e)
	{
		if (e == null || e.Item.DataItem == null) return;
		Comment c = (Comment)e.Item.DataItem;
		Label lbl = (Label)e.Item.FindControl("lblComment");
		lbl.Text = Server.HtmlEncode(c.Body);
		if (lbl.Text.Length > 1000) lbl.Text = lbl.Text.Substring(0, 995) + " [...]";


		Label lblDatetime = (Label)e.Item.FindControl("lblDatetime");
		lblDatetime.Text = c.DateTime.ToString("MM/dd/yyyy HH:mm:ss");
	}


	protected void btnSubmit_Click(object sender, EventArgs e)
	{
		if (!reCaptcha.IsValid) {
			err("Enter CAPTCHA to continue");
			return; }
		if (Master.act.Session.IP.NumProblems > 0) {
			err("Problems have been recorded from your IP address. No can do.");
			return; }
		if (Master.act.Session.User != null && Master.act.Session.User.BanLevel > 0) {
			err("Problems have been recorded from the logged in user.  No can do.");
			return; }

		string text = txtComment.Text;
		foreach (BannedWord bw in dc.BannedWords)
			if (text.ToLower().Contains(bw.word.ToLower())) {
				text = text.ToLower().Replace(bw.word.ToLower(), "(Banned Word)");
				Master.act.Session.IP.NumProblems++;
				Master.act.Session.IP.Notes += "; used banned word \"" + bw.word + "\"";
				dc.SubmitChanges(); }


		// Comment is good enough for now. Post it, post it good.
		Comment comment = new Comment();
		comment.AID = Master.act.ID;
		comment.Body = text;
		comment.DateTime = DateTime.Now;
		comment.isRequireMod = true;
		dc.Comments.InsertOnSubmit(comment);

		Activity act = (from a in dc.Activities where a.ID == Master.act.ID select a).First();
		act.PID = p.ID;
 		dc.SubmitChanges();
		PopulatePost(p, dc);

		// Notify me there has been a new comment posted
		for (int i = 0; i < 3; i++)
			Console.Beep(2000 + (i * 250), 500);

		err("Comment " + comment.ID.ToString() + " has been posted and is awaiting Moderation.");
	}
	private void err(string msg)
	{
		lblError.Visible = true;
		lblError.Text = msg;
	}
}